--
-- @Author:      name
-- @DateTime:    2019-07-11 10:05:48
-- @Description: 消息的处理

local skynet = require "skynet"
local log = require "Logger"
local config = require "configquery"
local NodeMessage = require "NodeMessage"
local RabbitMQ = require "RabbitMQ"
local cjson = require "cjson"

local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor(message_dispatch)
	self.rabbitmq_enabled = skynet.getenv("rabbitmq_enabled")
	self.rabbitmq_ip = skynet.getenv("rabbitmq_ip")
	self.rabbitmq_port = tonumber(skynet.getenv("rabbitmq_port"))
	self.rabbitmq_username = skynet.getenv("rabbitmq_username")
	self.rabbitmq_password = skynet.getenv("rabbitmq_password")
	self.rabbitmq_vhost	= skynet.getenv("rabbitmq_vhost")
	self.proto_file = skynet.getenv("proto_config") --proto文件路径	
	self.message_dispatch = message_dispatch
	self.node_message = NodeMessage.new()
	self.rabbitmq = RabbitMQ.new()

	self:register()
end

--注册本服务里的消息
function MessageHandler:register()
	--启动
	self.message_dispatch:registerSelf('start', handler(self,self.start))
	self.message_dispatch:registerSelf('push_data', handler(self,self.push))
end

--订阅消息
function MessageHandler:subscribe()
    local headers = {
	    destination = "test",
	    id=1,
	}    
    self.rabbitmq:subscribe(headers, function(data)
        -- skynet.error("consumed:", data)  
        self:dispatch(data)      
    end)
    self.rabbitmq:receive()
end

--发送消息
function MessageHandler:push(data)	
    local msg = data or {}
    local headers = {}
    headers["destination"] = "test"
    -- headers["receipt"] = "msg#1"
    -- headers["app-id"] = "skynet_rabbitmq"
    headers["persistent"] = "true"
    headers["content-type"] = "application/json"
    self.rabbitmq:send(cjson.encode(msg), headers)
end

--收到rabbitmq的消息
function MessageHandler:dispatch(data)	
	skynet.error("#####dispatch:", data) 
end

-----------------------------------------------------
--cmd
-----------------------------------------------------
function MessageHandler:start()
		-- self.rabbitmq:connect({host = "127.0.0.1", port = 61613},  
		-- { username = "admin", password = "admin", vhost = "/" }) 
	if self.rabbitmq_enabled=="0" then 
		return 
	end
	local conf = {
		host = self.rabbitmq_ip,
		port = self.rabbitmq_port,
	}
	local options = {	
		username = self.rabbitmq_username,
		password = self.rabbitmq_password,
		vhost = self.rabbitmq_vhost	,
	}	
	self.rabbitmq:connect(conf, options)
	-- self:push()
	self:subscribe()
end




return MessageHandler